from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.video.compositing.CompositeVideoClip import concatenate_videoclips

# 根据时间区间将整个视频的多个时间分段进行合并
def clip_and_merge_video(input_path, output_path, time_ranges):
    # 导入视频
    video = VideoFileClip(input_path)

    # 剪辑视频片段
    clips = []
    for start_time, end_time in time_ranges:
        clip = video.subclipped(start_time, end_time)
        clips.append(clip)

    # 合并视频片段
    final_clip = concatenate_videoclips(clips)

    # 保存合并后的视频
    final_clip.write_videofile(output_path, codec='libx264')

    # 关闭视频对象
    video.close()
    final_clip.close()

if __name__ == '__main__':
    # 示例使用
    input_path = "../origin_video/clipping_video.mp4"
    output_path = "../origin_video/output.mp4"
    time_ranges = [(7.973, 17), (45, 50.55)]  # 两个时间段的开始和结束时间（秒）

    clip_and_merge_video(input_path, output_path, time_ranges)